#include "StdAfx.h"
#include "GameplayState.h"
#include "Utility\Camera.h"
#include "Graphics\Geometries.h"
#include "Graphics\Model.h"
#include "Graphics\DxRenderer.h"
#include "Physics\PhysicsGeometry.h"
#include "Physics\PhysicsWorld.h"
#include "Level.h"
#include "Player.h"
#include "Input\DxInputManager.h"



GameplayState::GameplayState(void)
{
	m_pCamera = new Camera(Vector4(9.0f, 13.5f, 9.0f, 1.0f), Vector4(0.0f, 0.00f, 0.0f, 1.0f), v_OneY);

	m_world = new PhysicsWorld(100.0f);

	Geometries* geometry = new Geometries();
	geometry->Load("Assets\\Models\\swatMan.dae");
	m_aGeometries.SetSize(1);
	m_aGeometries.Add(geometry);	

	PhysicsGeometry* physicsCollision = new PhysicsGeometry();
	physicsCollision->Load("Assets\\Models\\swatManCollision.dae");
	m_aCollisionGeometry.SetSize(1);
	m_aCollisionGeometry.Add(physicsCollision);

	m_pPlayer = new Player(102.0f, geometry, physicsCollision);

	//m_pCurrentLevel = new Level("Assets\\Levels\\Level1.xml");

}


GameplayState::~GameplayState(void)
{
	for(int i = 0; i < m_aGeometries.GetNumElements(); i++)
	{
		delete m_aGeometries[i];
	}

	for(int i = 0; i < m_aCollisionGeometry.GetNumElements(); i++)
	{
		delete m_aCollisionGeometry[i];
	}

	delete m_pPlayer;
	//delete m_pCurrentLevel;
}

bool GameplayState::Update(float fDeltaTime)
{
	m_pPlayer->Update(fDeltaTime);
	
	//m_world->Update(fDeltaTime );

	return true;
}

void GameplayState::Draw()
{
	DxRenderer::GetInstance()->SetView(m_pCamera->GetView());
	//m_pCurrentLevel->Draw();
	m_pPlayer->Draw();
}

bool GameplayState::InputEvent(eInputEventType type, u32 uBtn)
{
	bool bRet = false;
	sPoint ptMousePos = g_pInputManager->GetMouseLoc();
	switch( type )
	{
		case eIET_ButtonUp:
		{
			switch(uBtn)
			{
				case DXM_BUTTON_0:
					{
						MouseUpdate(Vector4(ptMousePos.m_iX, ptMousePos.m_iY, 0.0f, 0.0f) );
						bRet = true;
						break;	
					}
				
			}
			break;
		}


	}


	return bRet;
}

bool GameplayState::MouseUpdate(const Vector4& mouse)
{
	Vector4 vGround = mouse;
	ScreenSpaceToWorld(vGround);

	m_pPlayer->SetTargetPosition(vGround);

	return true;
}

void GameplayState::ScreenSpaceToWorld(Vector4& vScreen)
{
	DxRenderer* pRenderer = DxRenderer::GetInstance();
	Matrix mIProj = pRenderer->GetProjection();
	Matrix mIView = m_pCamera->GetView();	
	Vector4 vRayDir;
	vRayDir.SetX(-(((2.0f * vScreen.GetX()) / pRenderer->GetScreenWidth()) - 1) / mIProj.GetA().GetX());
	vRayDir.SetY((((2.0f * vScreen.GetY()) / pRenderer->GetScreenHeight()) - 1) / mIProj.GetB().GetY());
	vRayDir.SetZ(1.0f);
	vRayDir.SetW(0.0f);
	mIView.Invert();
	vRayDir *= mIView;

	// Project the ray onto the ground plane to find the ground point
	Vector4 vRayOrigin = mIView.GetD();
	float fT = -vRayOrigin.GetY() / vRayDir.GetY();
	vScreen = vRayOrigin + (vRayDir * fT);
}